package com.yitong.xjd.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yitong.xjd.domain.RequestDataGjj;
import com.yitong.xjd.domain.ReturnData4Gjj;
import com.yitong.xjd.services.GongJiJinDaiService;

@RestController
@RequestMapping("/XACRM")
public class GongJiJinDaiController{
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GongJiJinDaiService gongJiJinDaiService;
	
	
	/**
	 * 公积金贷额度计算接口
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value="/queryGjjed.do",method = RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/json;charset=UTF-8");  
        ObjectMapper objectMapper = new ObjectMapper();
        String ids=null;
        //接受post请求数据
        logger.info("接受请求报文...");
        StringBuffer sb=new StringBuffer("");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));  
			String temp;  
			while ((temp = br.readLine()) != null) {  
			    sb.append(temp);  
			}  
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
			ids="接收报文数据失败";
		}  
        //请求数据转化为对象
		logger.info("解析请求报文...");
		RequestDataGjj o=null;
        String acceptjson = sb.toString(); 
        if (!acceptjson.equals("")){
        	try {
        		
				o=objectMapper.readValue(acceptjson, RequestDataGjj.class);
			} catch (Exception e) {
				e.printStackTrace();
				ids="提取报文数据失败";
			}
        }else{
        	ids="报文数据为空";
        }
        //更新数据库
        logger.info("处理请求报文...");
        ReturnData4Gjj bean=null;
        if(o!=null){
        	bean=gongJiJinDaiService.queryGjjed(o);
		}else{
			bean = new ReturnData4Gjj("","0",ids,"0");
		}
        //返回
        logger.info("返回结果报文...");
        PrintWriter out=null;
        try {
			String s = objectMapper.writeValueAsString(bean);
			out = response.getWriter();  
			out.write(s); 
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();out=null;
			}
		}
	}
	
}
